package com.ywl.gulimall.product.service.impl;

import com.ywl.gulimall.product.service.CategoryBrandRelationService;
import com.ywl.gulimall.product.vo.Catelog2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ywl.common.utils.PageUtils;
import com.ywl.common.utils.Query;

import com.ywl.gulimall.product.dao.CategoryDao;
import com.ywl.gulimall.product.entity.CategoryEntity;
import com.ywl.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1.查询所有分类
        List<CategoryEntity> allList = baseMapper.selectList(null);
        // 2.获取一级分类
        List<CategoryEntity> level1List =  allList.stream().filter((categoryEntity)->{
            return categoryEntity.getParentCid() == 0;
        }).map((menu)->{
            // 3.设置子分类
            menu.setChildren(getChildren(menu, allList));
            return menu;
        }).sorted((menu1, menu2)->{
            // 4.一级分类排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return level1List;
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        // 构造返回结果集合：[2, 34, 225]
        List<Long> allPath = new ArrayList<>();
        // 递归获取结果为：[225, 34, 2]
        findCatelogPath(catelogId, allPath);
        // 逆序
        Collections.reverse(allPath);
        return allPath.toArray(new Long[allPath.size()]);
    }

    @Transactional
    @Override
    public void updateDetail(CategoryEntity category) {
        // 先更新自己
        this.updateById(category);
        // 及联更新分类品牌关系表
        categoryBrandRelationService.updateCatelog(category.getCatId(), category.getName());
    }

    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("getLevel1Categorys........");
        long l = System.currentTimeMillis();
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(
                new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        System.out.println("消耗时间："+ (System.currentTimeMillis() - l));
        return categoryEntities;
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        System.out.println("查询了数据库");

        //将数据库的多次查询变为一次
        List<CategoryEntity> selectList = this.baseMapper.selectList(null);

        //1、查出所有分类
        //1、1）查出所有一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);

        //封装数据
        Map<String, List<Catelog2Vo>> parentCid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、每一个的一级分类,查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());

            //2、封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName().toString());

                    //1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());

                    if (level3Catelog != null) {
                        List<Catelog2Vo.Category3Vo> category3Vos = level3Catelog.stream().map(l3 -> {
                            //2、封装成指定格式
                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                            return category3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(category3Vos);
                    }

                    return catelog2Vo;
                }).collect(Collectors.toList());
            }

            return catelog2Vos;
        }));

        return parentCid;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList,Long parentCid) {
        List<CategoryEntity> categoryEntities = selectList.stream().filter(item -> item.getParentCid().equals(parentCid)).collect(Collectors.toList());
        return categoryEntities;
        // return this.baseMapper.selectList(
        //         new QueryWrapper<CategoryEntity>().eq("parent_cid", parentCid));
    }

    /**
     * 递归查询所属分类的父分类
     * @param catelogId
     * @param allPath [225, 34, 2]
     */
    private void findCatelogPath(Long catelogId, List<Long> allPath) {
        // 1、首先把当前分类添加到返回结果中
        allPath.add(catelogId);
        // 2、判断当前分类的父分类是否等于0
        CategoryEntity byId = getById(catelogId);
        if (byId.getParentCid() != 0) {
            findCatelogPath(byId.getParentCid(), allPath);
        }
    }

    /**
     * 递归设置当前分类的子分类
     * @param categoryEntity 当前分类
     * @param allList 所有分类
     * @return
     */
    public List<CategoryEntity> getChildren(CategoryEntity categoryEntity, List<CategoryEntity> allList) {
        // 获取当前分类的子分类
        List<CategoryEntity> children = allList.stream().filter((menu)->{
            // Long型比较用基本数据类型
            return menu.getParentCid().longValue() == categoryEntity.getCatId().longValue();
        }).map((menu)->{
            // 递归获取子分类
            menu.setChildren(getChildren(menu, allList));
            return menu;
        }).sorted((menu1, menu2)->{
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

}